#include <my_head.h>

#define U_R 0400
#define U_W 0200
#define U_X 0100
#define G_R 0040
#define G_W 0020
#define G_X 0010
#define O_R 0004
#define O_W 0002
#define O_X 0001

int main(int argc, const char *argv[]){
    if(2 != argc){
        printf("Usage : %s pathname\n", argv[0]);
        return -1;
    }
    //打开目录
    DIR *my_dir=NULL;
    if(NULL==(my_dir=opendir(argv[1])))
        ERR_LOG("opendir error");

    struct dirent *dp=NULL;
    char buff[1024] = {0};
    // 获取属性
    struct stat my_stat;
    if(-1 == lstat(argv[1], &my_stat))
            ERR_LOG("stat error");
    char lj[1024]={0};


    while(dp=readdir(my_dir)){
        sprintf(lj, "%s/%s", argv[1], dp->d_name);
        if(-1 == lstat(lj, &my_stat))
            ERR_LOG("stat error");

        
        //类型
        char type = 0;
        if(S_ISREG(my_stat.st_mode)){
            type = '-';
        }else if(S_ISDIR(my_stat.st_mode)){
            type = 'd';
        }else if(S_ISLNK(my_stat.st_mode)){
            type = 'l';
        }

        // 权限
        char u_r = '-';
        char u_w = '-';
        char u_x = '-';
        char g_r = '-';
        char g_w = '-';
        char g_x = '-';
        char o_r = '-';
        char o_w = '-';
        char o_x = '-';
        int qx = my_stat.st_mode & 0777;
        if(qx & U_R) u_r = 'r';
        if(qx & U_W) u_w = 'w';
        if(qx & U_X) u_x = 'x';
        if(qx & G_R) g_r = 'r';
        if(qx & G_W) g_w = 'w';
        if(qx & G_X) g_x = 'x';
        if(qx & O_R) o_r = 'r';
        if(qx & O_W) o_w = 'w';
        if(qx & O_X) o_x = 'x';
        
        // 硬链接数
        int nlink = my_stat.st_nlink;

        // 用户名
        char usr_name[32];
        strcpy(usr_name, getpwuid(my_stat.st_uid)->pw_name);

        // 组名
        char grp_name[32];
        strcpy(grp_name, getgrgid(my_stat.st_gid)->gr_name);

        // 大小
        int size = my_stat.st_size;

        // 时间戳
        struct tm *p = NULL;
        if(NULL == (p = localtime(&(my_stat.st_mtime))))
            ERR_LOG("localtime error");
        char data_time[64];
        sprintf(data_time, "%d月  %2d %02d:%02d", \
            p->tm_mon+1, p->tm_mday, p->tm_hour, p->tm_min);

        // 组装属性到数组中
        sprintf(buff, "%c%c%c%c%c%c%c%c%c%c %d %s %s %d %s %s", type, \
                    u_r, u_w, u_x, g_r, g_w, g_x, o_r, o_w, o_x,\
                    nlink, usr_name, grp_name, size, data_time, dp->d_name);
        // 输出
        printf("%s\n", buff);
    }
    //关
    closedir(my_dir);
    return 0;
}